﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace UtilLib
{
    /// <summary>
    /// 权重筛选器
    /// </summary>
    public partial class Weighted<T>
    {
        /// <summary>
        /// 执行权重筛选，取一个元素
        /// </summary>
        public T SelectSingle()
        {
            CalculateCumulativeWeights();

            if (Items.Count == 0)
            {
                return default;
            }

            return BinarySelect(Items).Value;
        }
        /// <summary>
        /// 执行权重筛选，取多个元素
        /// </summary>
        public List<T> SelectMultiple(int count, bool AllowDuplicate = false)
        {
            CalculateCumulativeWeights();

            if (AllowDuplicate)
            {
                return SelectMultipleAllowDuplicateTrue(count);
            }
            else
            {
                return SelectMultipleAllowDuplicateFalse(count);
            }
        }
        /// <summary>
        /// 执行权重筛选，取多个元素，可重复
        /// </summary>
        public List<T> SelectMultipleAllowDuplicateTrue(int count)
        {
            var resultList = new List<T>();
            for (int i = 0; i < count; i++)
            {
                resultList.Add(BinarySelect(Items).Value);
            }
            return resultList;
        }
        /// <summary>
        /// 执行权重筛选，取多个元素，不可重复
        /// </summary>
        public List<T> SelectMultipleAllowDuplicateFalse(int count)
        {
            var resultcount = count;
            var resultList = new List<T>();
            if (Items.Count < resultcount)
            {
                resultcount = Items.Count;
            }
            var items = new List<WeightedItem<T>>(Items);
            do
            {
                var item = LinearSelect(items);
                resultList.Add(item.Value);
                items.Remove(item);
            } while (resultList.Count < resultcount);
            return resultList;
        }

    }
}
